package com.donger.mes.system.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.donger.mes.system.base.entity.MesBaseBom;
import com.donger.mes.system.base.entity.MesBaseMaterial;
import com.donger.mes.system.base.mapper.MesBaseBomMapper;
import com.donger.mes.system.base.service.MesBaseBomService;
import com.donger.mes.system.base.service.MesBaseMaterialService;
import com.donger.common.core.utils.BizException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@AllArgsConstructor
public class MesBaseBomServiceImpl implements MesBaseBomService {

    private final MesBaseBomMapper mesBaseBomMapper;
    private final MesBaseMaterialService mesBaseMaterialService;
    @Override
    public IPage<MesBaseBom> page(IPage<MesBaseBom> page, QueryWrapper<MesBaseBom> queryWrapper) {
        return mesBaseBomMapper.selectPage(page,queryWrapper);
    }

    @Override
    public void save(MesBaseBom mesBaseBom) {
        Optional.ofNullable(mesBaseBom.getParentCode()).orElseThrow(() -> new BizException(""));
        MesBaseMaterial mesBaseMaterial = mesBaseMaterialService.infoByCode(mesBaseBom.getParentCode());
        mesBaseBom.setParentName(mesBaseMaterial.getMatName());

        Optional.ofNullable(mesBaseBom.getMatCode()).orElseThrow(() -> new BizException(""));

        MesBaseMaterial mesBaseMaterial1 = mesBaseMaterialService.infoByCode(mesBaseBom.getMatCode());

        mesBaseBom.setMatName(mesBaseMaterial1.getMatName());


        if(mesBaseBom.getId() == null){
            mesBaseBomMapper.insert(mesBaseBom);
        }else{
            mesBaseBomMapper.updateById(mesBaseBom);
        }
    }

    @Override
    public MesBaseBom infoById(Long id) {
        MesBaseBom mesBaseBom = mesBaseBomMapper.selectById(id);
        return mesBaseBom;
    }

    @Override
    public List<MesBaseBom> list(String parentCode) {
        Optional.ofNullable(parentCode).orElseThrow(() -> new BizException("物料编码错误"));
        List<MesBaseBom> mesBaseBoms = mesBaseBomMapper.selectList(Wrappers.<MesBaseBom>lambdaQuery().eq(MesBaseBom::getParentCode, parentCode));
        return mesBaseBoms;
    }


}
